/* eslint-disable no-control-regex */

import React from 'react'
// import { loading, openBrowser, errorMsg, successMsg, warnMsg } from '../scripts/common.js'
import { Modal } from 'antd'
import FsUtil from './utils/FsUtil.js'
import config from './config.js'
import { loading, openBrowser, errorMsg, successMsg, warnMsg, infoMsg } from './common.js'

const { spawn, exec } = require('child_process')
const { ipcRenderer } = require('electron')
const { sep } = require('path')

const reg_x00 = /\x00/g
const reg_r = /\r/g
const params = ['-l', '-v']

const pageSize = 6
const renameFormRef = React.createRef()
const copyFormRef = React.createRef()

const vars = {
  qryIndex: 0,
  showRson: false,
  ctx: null,
  wsls: [],
  migrated: [],
  migratePth: null,
  currentName4ReName: '',
  currentName4Copy: ''
}

const allBtn = React.createRef()
const runBtn = React.createRef()
const queryBtns = [allBtn, runBtn]
const formRef = React.createRef()

/**
 * 查看没有数据原因
 */
const showReason = () => {
  const command = 'start cmd.exe /K wsl.exe -l -v'
  exec(command, { windowsHide: false }, () => {})
}

/**
 * 判断选择的wsl是否是停止状态
 * @param {*} rowData
 * @returns
 */
const isWslStopped = (rowData) => {
  const name = rowData.name
  const state = rowData.state
  if (state !== 'Stopped') {
    // message.open({
    //     type: 'warning',
    //     content: `${name}${vars.ctx.t('noOptTip')}`,
    //     duration: 2
    // })
    warnMsg(`${name}${vars.ctx.t('noOptTip')}`)
    return false
  }
  return true
}

/**
 * 拷贝wsl
 * @param {*} curName
 * @param {*} newName
 */
const copy = (curName, newName) => {
  loading(vars.ctx, true)
  const path = FsUtil.mkTempDir()
  const filePath = `${path}${sep}${curName}.tar`
  // console.log(filePath)
  // 1. 导出
  const command = `cmd.exe /C wsl --export ${curName} ${filePath}`
  exec(command, (error) => {
    loading(vars.ctx, false)
    if (error) {
      errorMsg(vars.ctx)
      // console.log(error)
    } else {
      // console.log('导出完成')
      // 2. 执行导入
      const migratePath = config.getData().migratePath
      const basePath = `${migratePath}${sep}${newName}`
      FsUtil.mkDirs(basePath)
      const command = `cmd.exe /C wsl --import ${newName} ${basePath} ${filePath}`
      // console.log(command)
      exec(command, (error) => {
        loading(vars.ctx, false)
        if (error) {
          errorMsg(vars.ctx)
          // console.log(error)
        } else {
          // console.log('导入完成')
          successMsg(vars.ctx)
          // 3. 删除临时导出的文件
          FsUtil.delDir(path)
        }
      })
    }
  })
}

/**
 * 重命名
 * @param {*} oldName
 * @param {*} newName
 */
const reName = (oldName, newName) => {
  loading(vars.ctx, true)
  const path = FsUtil.mkTempDir()
  const filePath = `${path}${sep}${oldName}.tar`
  // console.log(filePath)
  // 1. 导出
  const command = `cmd.exe /C wsl --export ${oldName} ${filePath}`
  exec(command, (error) => {
    loading(vars.ctx, false)
    if (error) {
      errorMsg(vars.ctx)
      // console.log(error)
    } else {
      // console.log('导出完成')
      // 2. 执行导入
      const migratePath = config.getData().migratePath
      const basePath = `${migratePath}${sep}${newName}`
      FsUtil.mkDirs(basePath)
      const command = `cmd.exe /C wsl --import ${newName} ${basePath} ${filePath}`
      // console.log(command)
      exec(command, (error) => {
        loading(vars.ctx, false)
        if (error) {
          errorMsg(vars.ctx)
          // console.log(error)
        } else {
          // console.log('导入完成')
          // 3. 删除
          const command = `cmd.exe /C wsl --unregister ${oldName}`
          // console.log(command)
          exec(command, (error) => {
            loading(vars.ctx, false)
            if (error) {
              errorMsg(vars.ctx)
              // console.log(error)
            } else {
              // console.log(stdout)
              successMsg(vars.ctx)
              // 4. 删除临时导出的文件
              FsUtil.delDir(path)
            }
          })
        }
      })
    }
  })
}

/**
 * 删除指定名称的wsl
 * @param {*} rowData
 */
const unregisterWsl = (rowData) => {
  // console.log(rowData)
  // console.log(vars.migratePth)
  // console.log(`${vars.migratePth}${sep}${rowData.name}`)
  if (!isWslStopped(rowData)) {
    return
  }
  Modal.confirm({
    title: vars.ctx.t('sysTip'),
    content: `${vars.ctx.t('deleteTip')}${rowData.name}${vars.ctx.t('question')}`,
    okText: vars.ctx.t('okText'),
    cancelText: vars.ctx.t('cancelText'),
    onOk: () => {
      loading(vars.ctx, true)
      const command = `cmd.exe /C wsl --unregister ${rowData.name}`
      // console.log(command)
      exec(command, (error) => {
        loading(vars.ctx, false)
        if (error) {
          errorMsg(vars.ctx)
          // console.log(error)
        } else {
          // console.log(stdout)
          successMsg(vars.ctx)
          // 删除对应目录
          if (rowData.migrated) {
            FsUtil.delDir(`${vars.migratePth}${sep}${rowData.name}`)
          }
        }
      })
    }
  })
}

/**
 * 导入wsl
 * @param {*} filePath
 * @param {*} fileName
 */
const importWsl = (filePath, fileName) => {
  loading(vars.ctx, true)
  const setting = config.getData()
  const migratePath = setting.migratePath
  const basePath = `${migratePath}${sep}${fileName}`
  // console.log(basePath)
  try {
    FsUtil.mkDirs(basePath)
  } catch {
    loading(vars.ctx, false)
    // console.log(err)
    return
  }
  const command = `cmd.exe /C wsl --import ${fileName} ${basePath} ${filePath}`
  // console.log(command)
  exec(command, (error, stdout, stderr) => {
    loading(vars.ctx, false)
    // console.log(stdout)
    // console.log(stderr)
    if (error) {
      errorMsg(vars.ctx)
    } else {
      successMsg(vars.ctx)
    }
  })
}

/**
 * 执行wsl导入
 * @param {*} filePath
 * @param {*} fileName
 */
const exeImportWsl = (filePath, fileName) => {
  // console.log(`filePath = ${filePath}, fileName = ${fileName}`)
  importWsl(filePath, fileName)
}

/**
 * 关闭指定的wsl
 * @param {*} rowData
 * @param {*} flag
 */
const startOrStop = (rowData, flag) => {
  if (flag !== 'start' && flag !== 'stop') return

  let command = `start cmd.exe /C wsl -d ${rowData.name} --cd ~`
  if (flag === 'stop') {
    Modal.confirm({
      title: vars.ctx.t('sysTip'),
      content: `${vars.ctx.t('shutdownTipPrefix')}${rowData.name}${vars.ctx.t('question')}`,
      okText: vars.ctx.t('okText'),
      cancelText: vars.ctx.t('cancelText'),
      onOk: () => {
        loading(vars.ctx, true)
        command = `cmd.exe /C wsl -t ${rowData.name} && exit`
        exec(command, (error) => {
          if (flag === 'stop') {
            loading(vars.ctx, false)
            if (error) {
              errorMsg(vars.ctx)
              // console.log(`error: ${error.message}`)
            } else {
              successMsg(vars.ctx)
            }
          }
        })
      }
    })
  } else {
    exec(command)
  }
}

/**
 * 设置默认
 * @param {*} rowData
 */
const setDefault = (rowData) => {
  loading(vars.ctx, true)
  // console.log(rowData)
  const command = `cmd.exe /C wsl --set-default ${rowData.name}`

  exec(command, (error, stdout) => {
    loading(vars.ctx, false)
    if (error) {
      errorMsg(vars.ctx)
      // console.log(`error: ${error.message}`)
    } else if (stdout) {
      successMsg(vars.ctx)
    }
  })
}

/**
 *
 * @param {*} thisNode
 * @returns
 */
const changeQueryStatus = (thisNode) => {
  if (!thisNode || !thisNode.current || !thisNode.current.classList) return
  queryBtns.map((val) => {
    if (val === thisNode) {
      if (!val.current.classList.contains('wsl-tools-item-active')) {
        thisNode.current.classList.add('wsl-tools-item-active')
      }
    } else {
      val.current.classList.remove('wsl-tools-item-active')
    }
  })
}

/**
 * 打开文件对话框：导出wsl
 * @param {*} rowData
 */
const openDialog = (rowData) => {
  if (!isWslStopped(rowData)) {
    return
  }
  const data = {
    oldName: rowData.name,
    title: vars.ctx.t('selectExpDir'),
    supportType: vars.ctx.t('supportFileType')
  }
  ipcRenderer.send('openDialog', data)
}

/**
 * 打开文件选择对话框：导入wsl
 */
const openFileDialog = () => {
  const data = {
    title: vars.ctx.t('import'),
    supportType: vars.ctx.t('supportFileType')
  }
  ipcRenderer.send('openFileDialog', data)
}

/**
 * 监听主进程发送的importWsl事件
 */
ipcRenderer.on('importWsl', (e, filePath) => {
  // console.log(filePath)
  let fileName = filePath.substring(filePath.lastIndexOf('\\') + 1)
  fileName = fileName.substring(0, fileName.lastIndexOf('.'))
  formRef.current.setFieldsValue({
    pathField: filePath,
    nameField: fileName
  })
})

/**
 * 监听主进程发送的filePath事件：导出wsl
 */
ipcRenderer.on('filePath', (e, data) => {
  loading(vars.ctx, true)
  // console.log(data)
  let { oldName, filePath } = data
  const command = `cmd.exe /C wsl --export ${oldName} ${filePath}`
  exec(command, (error) => {
    loading(vars.ctx, false)
    if (error) {
      errorMsg(vars.ctx)
      // console.log(`error: ${error.message}`)
    } else {
      successMsg(vars.ctx)
    }
  })
})

/**
 * 关闭所有运行的wsl
 */
const shutdownAll = () => {
  let hasRunning = false
  try {
    vars.wsls.forEach((item) => {
      item.forEach((obj) => {
        if (obj.state === 'Running') {
          hasRunning = true
          throw new Error('has running wsl')
        }
      })
    })
  } catch {
    // console.log('')
  }

  if (hasRunning) {
    Modal.confirm({
      title: vars.ctx.t('sysTip'),
      content: vars.ctx.t('shutdownAllTip'),
      okText: vars.ctx.t('okText'),
      cancelText: vars.ctx.t('cancelText'),
      onOk: () => {
        loading(vars.ctx, true)
        const command = `cmd.exe /C wsl --shutdown`
        exec(command, (error) => {
          loading(vars.ctx, false)
          if (error) {
            errorMsg(vars.ctx)
            // console.log(`error: ${error.message}`)
          } else {
            successMsg(vars.ctx)
          }
        })
      }
    })
  } else {
    Modal.info({
      title: vars.ctx.t('sysTip'),
      content: vars.ctx.t('noRunningTip')
    })
  }
}

/**
 *  获取wsl列表
 * @param {*} setDatasFunc
 */
const wslList = (setDatasFunc) => {
  // console.log(setDatasFunc)
  let wsl = spawn('wsl', params)
  wsl.stdout.on('data', (data) => {
    setDatasFunc(getWsls(data, vars.qryIndex))
  })
}

// 解析wsl数据
const getWsls = (originalData, flag) => {
  const datas = []
  // console.log(typeof originalData)
  // console.log(originalData)
  const dataStr = originalData.toString()
  const dt = dataStr.split('\n')
  // let title = []
  let dataPerPage = []
  let title = []
  dt.forEach((val, index) => {
    const titleLineAry = val.replace(reg_x00, '').replace(reg_r, '').split(' ')
    // console.log(titleLineAry)
    if (titleLineAry && titleLineAry.length > 0) {
      const curLine = titleLineAry.filter((item) => {
        return item !== '' && item !== '\x00'
      })
      if (curLine.length > 0) {
        if (index === 0) {
          title = curLine
        } else {
          const wsl = {
            name: curLine[0] !== '*' ? curLine[0] : curLine[1],
            state: curLine[0] === '*' ? curLine[2] : curLine[1],
            version: curLine[0] === '*' ? curLine[3] : curLine[2],
            default: curLine[0] === '*'
          }
          if (flag === 0) {
            if (dataPerPage.length === 0) {
              datas.push(dataPerPage)
            } else if (dataPerPage.length % pageSize === 0) {
              dataPerPage = []
              datas.push(dataPerPage)
            }
            dataPerPage.push(wsl)
          } else if (wsl.state === 'Running') {
            if (dataPerPage.length === 0) {
              datas.push(dataPerPage)
            } else if (dataPerPage.length % pageSize === 0) {
              dataPerPage = []
              datas.push(dataPerPage)
            }
            dataPerPage.push(wsl)
          }
        }
      }
    }
  })

  // console.log(title)
  // console.log(datas)
  if (title && title[0] !== 'NAME') {
    vars.showRson = true
    return []
  } else {
    vars.showRson = false
  }

  vars.wsls = datas
  // 获取迁移目录中的文件夹
  const setting = config.getData()
  if (setting) {
    const migratePath = setting.migratePath
    // console.log(`migratePath=${migratePath}`)
    if (migratePath !== '') {
      vars.migratePth = migratePath
      const dirs = FsUtil.getDirs(migratePath)
      vars.migrated = dirs.map((dir) => {
        return dir.toLowerCase()
      })
    }
  }

  return datas
}

/**
 * 迁移wsl
 * @param {*} rowData
 */
const migrate = (rowData) => {
  // console.log(!vars.migratePth)
  if (!vars.migratePth) {
    //   message.open({
    //       type: 'info',
    //       content: vars.ctx.t('setMigPathTip')
    //   })
    infoMsg(vars.ctx.t('setMigPathTip'))
    return
  }
  if (!isWslStopped(rowData)) {
    return
  }
  const curName = rowData.name
  Modal.confirm({
    title: vars.ctx.t('sysTip'),
    content: `${vars.ctx.t('migrateTip')}${curName}${vars.ctx.t('question')}`,
    okText: vars.ctx.t('okText'),
    cancelText: vars.ctx.t('cancelText'),
    onOk: () => {
      loading(vars.ctx, true)
      // console.log(vars.migratePth)
      const path = `${vars.migratePth}${sep}${curName}`
      FsUtil.mkDirs(path)
      // const filePath = `${path}${sep}${curName}.tar`
      // console.log(path)
      // 迁移
      const command = `cmd.exe /C wsl --manage ${curName} --move ${path}`
      // console.log(command)
      exec(command, (error) => {
        loading(vars.ctx, false)
        if (error) {
          // console.log(error)
          errorMsg(vars.ctx)
        } else {
          successMsg(vars.ctx)
        }
      })
    }
  })
}

/**
 * 判断wsl名称是否存在
 * @param {*} name
 * @returns
 */
const isNameExists = (name) => {
  let exists = false
  try {
    // console.log(wsls)
    vars.wsls.forEach((val) => {
      val.forEach((item) => {
        // console.log(`${item.name.toLowerCase()}==${name.toLowerCase()}`)
        if (item.name.toLowerCase() === name.toLowerCase()) {
          exists = true
          throw new Error('名称相同')
        }
      })
    })
  } catch {
    // console.log(e.message)
  }
  return exists
}

/**
 * 初始化数据
 * @param {*} setDataFunc
 */
const initDatas = (setDataFunc) => {
  vars.qryIndex = 0
  wslList(setDataFunc)
}

/**
 * 定时查询数据
 * @param {*} setDataFunc
 */
const getDatasByTimer = (setDataFunc) => {
  let timer
  setTimeout(() => {
    timer = setInterval(() => {
      wslList(setDataFunc)
    }, 1500)
  }, 3000)

  // 销毁timer
  return () => {
    if (timer) {
      clearInterval(timer)
      //   console.log('timer destoried...')
    }
  }
}

/**
 * 名称校验
 * @param _
 * @param value
 * @returns {Promise<unknown>}
 */
const handleNameValidate = (_, value) => {
  value = value ? value.replace(/(^\s+)|(\s+$)/g, '') : ''
  // console.log(`=${value}=`)

  return new Promise((resolve, reject) => {
    const newNameReg = /^[a-zA-Z][a-zA-Z0-9-_.]*$/g
    const ret = newNameReg.test(value)
    // console.log(ret)
    if (!ret) {
      reject(vars.ctx.t('newNameCheck'))
    } else {
      const exists = isNameExists(value)
      if (exists) {
        reject(vars.ctx.t('newNameExist'))
      } else {
        resolve()
      }
    }
  })
}

/**
 * 对话框关闭后执行
 */
const handleAfterClose = () => {
  formRef.current.resetFields(['pathField1', 'pathField', 'nameField'])
}

/**
 * 校验导入表单
 */
const validateForm = (dismissDialogFunc) => {
  formRef.current.setFieldsValue({
    pathField1: 'hello'
  })
  formRef.current
    .validateFields()
    .then((resolve) => {
      // setImportOpen(false)
      dismissDialogFunc(false)
      const { pathField, nameField } = resolve
      // console.log(pathField, nameField)
      exeImportWsl(pathField, nameField)
    })
    .catch((_) => {
      // console.log('失败了', error)
    })
}

const handleImportModalOk = (dismissDialogFunc) => {
  // 校验表单，并执行导入
  validateForm(dismissDialogFunc)
}

const handleImportModalCancel = (dismissDialogFunc) => {
  // setImportOpen(false)
  dismissDialogFunc(false)
  formRef.current.setFieldsValue({
    pathField1: '',
    pathField: '',
    nameField: ''
  })
}

// 重命名
const handleReNameModalOk = (dismissFunc) => {
  // console.log(renameFormRef.current.getFieldValue('newName'))
  renameFormRef.current.validateFields().then((resolve) => {
    // setReNameOpen(false)
    dismissFunc(false)
    const { newName } = resolve
    reName(vars.currentName4ReName, newName)
  })
}

const handleReNameModalCancel = (dismissFunc) => {
  // setReNameOpen(false)
  dismissFunc(false)
  renameFormRef.current.setFieldsValue({
    newName: ''
  })
}

// 打开重命名对话框
const openReNameWin = (rowData, openReNameDialogFunc) => {
  if (isWslStopped(rowData)) {
    vars.currentName4ReName = rowData.name
    const name = rowData.name
    // setReNameOpen(true)
    openReNameDialogFunc(true)
    setTimeout(() => {
      renameFormRef.current.setFieldsValue({
        newName: name
      })
    }, 200)
  }
}

const handleCopyModalOk = (dismissCopyDialogFunc) => {
  copyFormRef.current.validateFields().then((resolve) => {
    // setCopyOpen(false)
    dismissCopyDialogFunc(false)
    const { copyName } = resolve
    copy(vars.currentName4Copy, copyName)
  })
}

const handleCopyModalCancel = (dismissCopyDialogFunc) => {
  // setCopyOpen(false)
  dismissCopyDialogFunc(false)
  copyFormRef.current.setFieldsValue({
    copyName: ''
  })
}

// 打开拷贝对话框
const openCopyWin = (rowData, openCopyDialogFunc) => {
  if (isWslStopped(rowData)) {
    let name = rowData.name
    vars.currentName4Copy = name
    // setCopyOpen(true)
    openCopyDialogFunc(true)
    setTimeout(() => {
      copyFormRef.current.setFieldsValue({
        copyName: name
      })
    }, 200)
  }
}

// 下拉菜单项click
const clickMenuItem = (key, ...openFuncs) => {
  // console.log(key)
  switch (key.key) {
    case '1':
      // 设置默认
      setDefault(key.data)
      break
    case '2':
      // 导出
      openDialog(key.data)
      break
    case '3':
      // 删除
      unregisterWsl(key.data)
      break
    case '4':
      // 重命名
      // openReNameWin(key.data, setReNameOpen)
      openReNameWin(key.data, openFuncs[0])
      break
    case '5':
      // 迁移
      migrate(key.data)
      break
    case '6':
      // 拷贝
      // openCopyWin(key.data, setCopyOpen)
      openCopyWin(key.data, openFuncs[1])
      break
  }
}

export {
  showReason,
  openBrowser,
  successMsg,
  errorMsg,
  startOrStop,
  queryBtns,
  changeQueryStatus,
  openFileDialog,
  formRef,
  shutdownAll,
  wslList,
  vars,
  getWsls,
  renameFormRef,
  copyFormRef,
  initDatas,
  getDatasByTimer,
  handleNameValidate,
  handleAfterClose,
  handleImportModalOk,
  handleImportModalCancel,
  handleReNameModalOk,
  handleReNameModalCancel,
  handleCopyModalOk,
  handleCopyModalCancel,
  clickMenuItem
}
